<?php

namespace App\Http\Controllers\Auth;

use App\models\UploadFile;
use App\models\user\EmailToken;
use App\models\user\Roles;
use App\models\user\SteamUser;
use App\models\user\UserRoles;
use App\other\TokenType;
use App\other\UtilsClass;
use App\models\user\User;
use App\Http\Controllers\Controller;
use Auth;
use DB;
use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Mail;
use Session;
use Storage;
use Validator;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request as R7Request;

class RegisterController extends Controller
{
    public function __construct(){
        $this->middleware('guest');
    }

    protected function validator(array $data)
    {
        return Validator::make($data, [
            'name'      => 'required|max:14',
            'email'     => 'required|email|max:64|unique:users',
            'password'  => 'required|min:8|confirmed',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @param  array  $data
     * @return User
     */
    protected function create(array $data){
        return User::create([
            'name'          => $data['name'],
            'email'         => $data['email'],
            'password'      => bcrypt($data['password']),
        ]);
    }

    public function register(Request $request)
    {
        if (Auth::check()){
            return redirect('/');
        }
        $v =  $this->validator($request->all());
        if ($v->fails()){
            return redirect('/steam/register')->withErrors($v->getMessageBag()->messages())
                ->withInput($request->all());
        }
        if (!Session::has("steam")){
            return redirect('/steam/register');
        }
        $user           = $this->create($request->all());
        $steamUser      = new SteamUser();
        $array          = Session::get('steam')[0];
        $profile        = $this->porfile($array['avatarfull']);
        $user->profile  = $profile;
        Session::forget('steam');
        DB::transaction(function () use($steamUser, $user, $array) {
            $user->save();
            $array['uid']   = $user->id;
            $steamUser->setRawAttributes($array);
            $steamUser->save();
            $userRole           = new UserRoles();
            $userRole->uid      = $user->id;
            $userRole->role_id  = 3;
            $userRole->save();
            self::sendRegisterEmail($user);
        });
        return redirect('/login')->with(['status' => '注册成功并已经发送激活邮件']);
    }

    public static function sendRegisterEmail(User $user){
        EmailToken::deleteToken($user->id, TokenType::TOKEN_PASSWDRESET_TYPE);
        $token              = EmailToken::where('uid', $user->id)->first();
        if (empty($token)){
            $token          = new EmailToken();
        }
        $token->uid         = $user->id;
        $token->type        = TokenType::TOKEN_REGISTER_TYPE;
        $token->token       = UtilsClass::getRandomStringCode(32);
        $token->dead_time   = time()+60*30;
        $token->save();
        $data = ['email' => $user->email, 'name'=>env('MAIL_NAME', 'MeShop'), 'token'=>$token->token , 'id'=>$token->id, 'username'=>$user->name];
        Mail::send('mail.email', $data, function(Message $message) use($data) {
            $message->to($data['email'], $data['username'])->subject('请激活您的账号！');
        });
    }

    protected function porfile($url){
        $client = new Client([
            'base_uri' => 'http://steamcdn-a.akamaihd.net',
            'timeout'  => 10.0,
        ]);
        $headers    = ['X-Foo' => 'Bar'];
        $body       = 'Hello!';
        $request    = new R7Request('GET', $url, $headers, $body);
        $response   = $client->send($request, ['timeout' => 10]);
        $lenth      = intval($response->getHeader('content-length')[0]);
        $img        = $response->getBody()->read($lenth);
        $name       = UtilsClass::getRandomStringCode('32').'.jpg';
        $file       = new UploadFile();
        $part       = '/porfile/'.$name;
        $file->md5  = md5($name.time());
        $file->filename = $name;
        $file->path = $part;
        $file->extension = 'jpg';
        $file->size = '0';
        Storage::disk('public')->put($part, $img);
        $file->save();
        return '/file/'.$file->md5;
    }
}
